import { DatePicker, Table, message, Form, Row, Col } from 'antd';
import Button from 'antd/es/button';
import { ColumnsType } from 'antd/es/table/interface';
import { FetchDataParam, FetchDataResponse, PageSelect } from 'components/UILibrary/pageSelect';
import moment from 'moment';
import React from 'react';
import {
  createSeatManageDownloadTask,
  getSeatManageReportList,
  getUsersWithoutPermission,
  getRobotsWithoutPermission,
} from 'admin/servers/servers';
import { clearNull, getTableIndex, toPercent } from 'utils/tools';
import { checkPermission } from 'permission/Index';

import { SeatManageInfo } from 'admin/schema/SeatManageReport';
import './style.scss';

const { RangePicker } = DatePicker;

interface IProp {}

interface IState {
  // 搜索条件
  /**
   * 坐席账号
   */
  userId?: number;
  /**
   * 开始时间
   */
  beginTime?: string;
  /**
   * 结束时间
   */
  endTime?: string;
  /**
   * 机器人
   */
  robotId?: number;
  /** table列头 */
  tableColumns: ColumnsType<SeatManageInfo>;
  tableData: SeatManageInfo[];
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  tableLoading: boolean;
}

export default class SeatManage extends React.Component<IProp, IState> {
  private robotRef: React.RefObject<any>;
  private seatRef: React.RefObject<any>;
  constructor(arg: IProp) {
    super(arg);
    this.robotRef = React.createRef();
    this.seatRef = React.createRef();
    this.state = {
      tableData: [],
      userId: undefined,
      robotId: undefined,
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableColumns: [
        {
          title: '序号',
          key: 'index',
          dataIndex: 'index',
          fixed: 'left',
          width: 70,
          render: (text: any, record: SeatManageInfo, index: number) =>
            getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
        },
        {
          title: '坐席账号',
          key: 'userName',
          dataIndex: 'userName',
          width: 150,
        },
        {
          title: '转入量',
          key: 'transferManualNumber',
          dataIndex: 'transferManualNumber',
          width: 150,
        },
        {
          title: '平均振铃时长(秒)',
          key: 'aveRingTime',
          dataIndex: 'aveRingTime',
          width: 150,
        },
        {
          title: '接听量',
          key: 'answerCallNumber',
          dataIndex: 'answerCallNumber',
          width: 150,
        },
        {
          title: '接听率',
          key: 'answerCallRate',
          dataIndex: 'answerCallRate',
          width: 150,
          render: (text: any, record: SeatManageInfo, index: number) => toPercent(text),
        },
        {
          title: '未接量',
          key: 'missedCallNumber',
          dataIndex: 'missedCallNumber',
          width: 150,
        },
        {
          title: '未接率',
          key: 'missedCallRate',
          dataIndex: 'missedCallRate',
          width: 150,
          render: (text: any, record: SeatManageInfo, index: number) => toPercent(text),
        },
        {
          title: '坐席总通话时长(秒)',
          key: 'seatsTotalTalkTime',
          dataIndex: 'seatsTotalTalkTime',
          width: 180,
        },
        {
          title: '坐席平均通话时长(秒)',
          key: 'seatsAveTalkTime',
          dataIndex: 'seatsAveTalkTime',
          width: 180,
        },
      ],
      tableLoading: false,
    };
  }

  componentDidMount() {
    this.fetchList();
  }
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  /**
   * 查询table数据
   */
  private async fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { pageInfo, userId, beginTime, endTime, robotId } = this.state;
    try {
      const res = await getSeatManageReportList(
        clearNull({
          pageNo: pageInfo.pageNum,
          pageSize: pageInfo.pageSize,
          beginTime,
          endTime,
          userId,
          robotId,
        })
      );
      pageInfo.pageTotal = res.count as number;
      this.setState({
        tableData: res.data,
        pageInfo: pageInfo,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      tableLoading: false,
    });
  }

  /**
   * 表格行操作后，重置列表
   */
  private resetList() {
    this.jumpPage(1);
  }
  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  /**
   * @private 时间范围选择器-绑定onChange事件
   * @param {*} dates moment格式
   * @param {*} dateStrings dateFormate格式
   * @memberof CallTask
   */
  private onDateChange(dates: any, dateStrings: any) {
    console.log(dates, '选择的日期范围', dateStrings);
    this.setState({
      beginTime: dateStrings[0],
      endTime: dateStrings[1],
    });
  }

  private handleExport(): void {
    // 创建下载任务
    const { userId, beginTime, endTime, robotId } = this.state;
    const postData = clearNull({
      beginTime,
      endTime,
      userId,
      robotId,
    });
    createSeatManageDownloadTask(postData as any).then(res => {
      if (res.code === 0) {
        // 创建下载任务
        message.warning('数据正在准备中，请稍候到下载管理中下载');
      } else {
        message.error(`${res.tips}(错误码:${res.code})`);
      }
    });
  }
  /**
   * 查找坐席账号的dataProvider
   */
  private fetchSeatUser(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getUsersWithoutPermission(
        clearNull({
          pageNo: args.pageNum,
          pageSize: args.pageSize,
          userName: args.keywords,
        })
      )
        .then(res => {
          resolve({
            data:
              res.data?.map(item => {
                return {
                  label: item.userName,
                  value: item.userId,
                };
              }) || [],
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }

  /**
   * 查找机器人的dataProvider
   */
  private fetchRobot(args: FetchDataParam): FetchDataResponse {
    return new Promise(resolve => {
      getRobotsWithoutPermission(
        clearNull({
          pageNo: args.pageNum,
          pageSize: args.pageSize,
          robotName: args.keywords,
        })
      )
        .then(res => {
          resolve({
            data:
              res.data?.map(item => {
                return {
                  label: item.robotName,
                  value: item.robotId,
                };
              }) || [],
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  }
  /**
   * 重置搜索列表
   */
  private resetSearch() {
    // 重置搜索条件；重置列表
    this.robotRef.current.clear();
    this.seatRef.current.clear();
    this.setState({
      userId: undefined,
      beginTime: '',
      endTime: '',
      robotId: undefined,
    });
    this.jumpPage(1);
  }
  render() {
    const {
      robotRef,
      seatRef,
      state: {
        tableColumns,
        tableData,
        pageInfo: { pageNum, pageSize, pageTotal },
        beginTime,
        endTime,
        tableLoading,
      },
    } = this;

    return (
      <>
        <div className="mgr-header seat-manage-header">
          <div className="mgr-header-left">
            <Form>
              <Row gutter={24}>
                <Col lg={{ span: 12 }} xl={{ span: 7 }}>
                  <Form.Item label="坐席账号">
                    <PageSelect
                      ref={seatRef}
                      allowClear
                      fetchData={this.fetchSeatUser}
                      placeholder="请选择坐席账号"
                      onChange={(val: any) => {
                        console.log(val, '坐席账号选择');
                        this.setState({
                          userId: val,
                        });
                      }}
                    />
                  </Form.Item>
                </Col>
                <Col lg={{ span: 12 }} xl={{ span: 10 }}>
                  <Form.Item label="呼叫时间">
                    <RangePicker
                      showTime
                      format="YYYY-MM-DD HH:mm:ss"
                      value={beginTime && endTime ? [moment(beginTime), moment(endTime)] : null}
                      ranges={{
                        今天: [moment().startOf('day'), moment().endOf('day')],
                        本周: [moment().startOf('week'), moment().endOf('week')],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                      }}
                      onChange={this.onDateChange.bind(this)}
                      allowClear
                    />
                  </Form.Item>
                </Col>
                <Col lg={{ span: 12 }} xl={{ span: 7 }}>
                  <Form.Item label="机器人">
                    <PageSelect
                      ref={robotRef}
                      allowClear
                      fetchData={this.fetchRobot}
                      placeholder="请选择机器人"
                      onChange={(val: any) => {
                        console.log(val, '机器人选择');
                        this.setState({
                          robotId: val,
                        });
                      }}
                    />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </div>
          <div className="mgr-header-right">
            <Button
              type="primary"
              onClick={() => {
                this.resetList();
              }}
            >
              搜索
            </Button>
            <Button
              type="primary"
              ghost
              onClick={() => {
                this.resetSearch();
              }}
            >
              重置
            </Button>
            {checkPermission('/report/seatManage/export') && (
              <Button
                type="primary"
                onClick={() => {
                  this.handleExport();
                }}
              >
                导出
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            dataSource={tableData}
            scroll={{ x: '100%', scrollToFirstRowOnChange: true }}
            columns={tableColumns}
            rowKey={(record: SeatManageInfo, index) => `table${record.userName}${index}`}
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
      </>
    );
  }
}
